//
//  XS_NotificationVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/11.
//

import UIKit

class XS_NotificationVC: XS_BaseVC {

    @IBOutlet weak var tableView: UITableView!
    lazy var dataModel = XS_NotificationM()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "消息中心"
        let rightItem = UIBarButtonItem.init(title: "全部已读", style: .plain, target: self, action: #selector(allReadAction))
        rightItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.qmui_color(withHexString: "333333")!], for: .normal)
        navigationItem.rightBarButtonItem = rightItem
        tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.register(UINib.init(nibName: "XS_NotificationListCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_NotificationListCell")
        tableView.register(XD_NotificationListTabCell.self, forCellReuseIdentifier: "XD_NotificationListTabCell")
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(headerRefesh))
        tableView.mj_footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(footerRefesh))
        headerRefesh()
    }
    
    @objc func headerRefesh(){
        requestData(true)
    }
    
    @objc func footerRefesh(){
        requestData(false)
    }
    
    @objc func allReadAction(){
        print("allReadActionallReadActionallReadActionallReadAction")
        XS_NetWork.requestJson("/notice/readAll")
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    self.headerRefesh()
                }else{
                    self.view.makeToast(resp.msg)
                }
                
            }).disposed(by: disposeBag)
    }
    
    func requestData(_ isFirst: Bool = false){
        if isFirst {
            dataModel.current = 0
            dataModel.records.removeAll()
        }
        XS_NetWork.requestJson("/notice/queryNotice", parameters: ["pageNo" : dataModel.current+1, "pageSize" : dataModel.size])
            .mapModel(type: XS_NotificationM.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                model.records = self.dataModel.records + model.records
                if model.records.count > 0 {
                    XD_BlankPageView.hiddenBlankPageView(superView: self.tableView)
                    self.navigationItem.rightBarButtonItem?.isEnabled = true
                    self.dataModel = model
                    self.tableView.reloadData()
                } else {
                    self.navigationItem.rightBarButtonItem?.isEnabled = false
                    XD_BlankPageView.blankPage(superView: self.tableView, imgName: "缺省页_暂无内容", detailStr: "暂无消息~", bottomDetailStr: "")
                }
                self.tableView.mj_header?.endRefreshing()
                if model.current >= model.pages { // 没有更多
                    self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                }else{
                    self.tableView.mj_footer?.endRefreshing()
                }
            }).disposed(by: disposeBag)
    }

}

extension XS_NotificationVC : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataModel.records.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "XD_NotificationListTabCell", for: indexPath) as! XD_NotificationListTabCell
        if indexPath.row < dataModel.records.count {
            cell.model = dataModel.records[indexPath.row]
        }
        cell.cellDelegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return XD_NotificationListTabCell.getCellHeight(dModel: dataModel.records[indexPath.row])
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        let model = dataModel.records[indexPath.row]
        //删除操作
        XS_NetWork.requestJson("/notice/delete", parameters: ["id":model.id])
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    self.dataModel.records.remove(at: indexPath.row)
                    tableView.reloadData()
                }else{
                    self.view.makeToast(resp.msg)
                }
            }).disposed(by: disposeBag)
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataModel.records[indexPath.row]
        XS_NetWork.requestJson("/notice/read", parameters: ["id":model.id])
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    model.state = "read"
                    self.tableView.reloadItemsAtIndexPaths([indexPath], animationStyle: .automatic)
                }
            }).disposed(by: disposeBag)
    }
}

extension XS_NotificationVC: XD_NotificationListTabCellDelegate {
    func showOrHiddenContents(cell: XD_NotificationListTabCell) {
        let indexPath: IndexPath = tableView.indexPath(for: cell)!
        let dModel = dataModel.records[indexPath.row]
        dModel.isOpened = !dModel.isOpened
        UIView.performWithoutAnimation { // 防止点击展开、收回闪烁
            tableView.reloadRows(at: [indexPath], with: .none)
        }
    }
}
